import random
from datetime import datetime
from flask import Blueprint, make_response, current_app
from flask import request
from utils.index import return_format
from get_config.index import config

upload = Blueprint('upload', __name__)

# 允许使用的图片后缀名
suffixList = ['png', 'jpg', 'jpeg', "webp", "jfif"]


@upload.route("/upload_img", methods=['POST'])
def upload_img():
    # 拼接图片服务器的基础路径
    image_url = "%s://%s:%d/img" % (config["protocol"], config["host"], config["port"])
    # 获取upload的路径
    base_dir = current_app.config['upload_dir']
    file = request.files.get('file')
    if file.filename.rsplit('.', 1)[1] in suffixList:
        # 生成随机数
        random_num = random.randint(0, 100)
        file_name = datetime.now().strftime("%Y%m%d%H%M%S") + "_" + str(random_num) + "." + file.filename.rsplit('.', 1)[1]
        file_path = base_dir + "\\" + file_name  # basedir 代表获取当前位置的绝对路径
        file.save(file_path)  # 把图片保存到static 中的file 文件名
        return make_response((return_format("上传成功", {"image_url": image_url + "/" + file_name}, 200)))
    else:
        return make_response((return_format("格式错误，仅支持%s格式文件" % (",".join(suffixList)), None, 500)))
